﻿using System;
using System.Configuration;
using System.Web.Mvc;
using Recaptcha;

namespace CodeContrib.Web.Mvc
{
	public class ValidateCaptchaAttribute : ActionFilterAttribute
	{
		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var captchaChallengeValue = filterContext.HttpContext.Request.Form["recaptcha_challenge_field"];
			var captchaResponseValue = filterContext.HttpContext.Request.Form["recaptcha_response_field"];

			var captchaValidtor = new RecaptchaValidator
				                      {
					                      Challenge = captchaChallengeValue,
					                      PrivateKey = Convert.ToString(ConfigurationManager.AppSettings["ReCaptchaPrivateKey"]),
					                      RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
					                      Response = captchaResponseValue
				                      };

			var recaptchaResponse = captchaValidtor.Validate();

			if (!recaptchaResponse.IsValid)
			{
				filterContext.Controller.ViewData.ModelState.AddModelError("recaptcha_response_field", "You did not enter the verification word correctly. Please try again.");
			}

			base.OnActionExecuting(filterContext);
		}
	}
}